/**
 * @author: hdh
 * @date: 2022-08-08 15:34
 */
package com.yy.QSManage.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.yy.QSManage.tool.RequestBuffUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;
import java.util.function.Supplier;

/**
 * sql自动填充
 * @author: HuDeHong
 * @date: 2022-08-08 15:34
 */
@Component
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Autowired
    private RequestBuffUtil requestBuffUtil;

    /**
     * 是否更新
     */
    private boolean isUpdate = true;

    @Override
    public void insertFill(MetaObject metaObject) {
        isUpdate = false;
        String memberId = null;
        try{
            memberId = requestBuffUtil.getTokenMemberId();
        } catch (Exception ignored) {
            // 忽略例如定时任务情况
        }
        // 起始版本 3.3.0(推荐使用)
        this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
        this.strictInsertFill(metaObject, "createUser", String.class, memberId);
        this.strictInsertFill(metaObject, "updateTime", Date.class, new Date());
        this.strictInsertFill(metaObject, "updateUser", String.class, memberId);
        this.strictInsertFill(metaObject, "isDelete", Integer.class, 0);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        isUpdate = true;
        String memberId = null;
        try{
            memberId = requestBuffUtil.getTokenMemberId();
        } catch (Exception ignored) {
            // 忽略例如定时任务情况
        }
        // 起始版本 3.3.0(推荐)
        this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
        this.strictUpdateFill(metaObject, "updateUser", String.class, memberId);
    }

    @Override
    public MetaObjectHandler strictFillStrategy(MetaObject metaObject, String fieldName, Supplier<?> fieldVal) {
        // 原方法，当填充字段不是null时，不会进行填充。即前端更新时携带了旧的update信息，就不会填充update
        // 改造后，增加更新操作强制填充
         if (metaObject.getValue(fieldName) == null || isUpdate) {
            Object obj = fieldVal.get();
            if (Objects.nonNull(obj)) {
                metaObject.setValue(fieldName, obj);
            }
         }
        return this;
    }
}
